import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pcp/common/config/config.dart';
import 'package:pcp/pages/draw_page.dart';
import 'package:pcp/pages/review_page.dart';
import 'package:popup_menu/popup_menu.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'add_review_page.dart';

class MineWorkStationPage extends StatefulWidget {
  const MineWorkStationPage({Key key})
      : super(key: key);

  @override
  _MineWorkStationPageState createState() => _MineWorkStationPageState();
}

class _MineWorkStationPageState extends State<MineWorkStationPage> {
  List projectList = new List();
  List infoList = new List();
  List<GlobalKey> btnKeys2 = new List();
  String str;

  Widget _scrollView() {
    return ListView.builder(
      padding: const EdgeInsets.all(10.0),
      itemExtent: 250.0,
      itemCount: projectList.length,
      itemBuilder: (context, int index) {
        return Column(
          children: <Widget>[
            Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1, color: Color(0xffaaaaaa)),
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  ),
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          alignment: Alignment.centerLeft,
                          constraints: BoxConstraints(
                            maxHeight: 60.0,
                          ),
                          child: Text(
                            " # " + projectList[index]["name"],
                            style: TextStyle(
                              fontSize: 25.0,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        constraints: BoxConstraints(maxHeight: 190.0,),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10.0)),
                            border: Border.all(width: 0,)
                        ),
                        child: CustomScrollView(
                          scrollDirection: Axis.horizontal,
                          slivers: <Widget>[
                            SliverFixedExtentList(
                              itemExtent: 200.0,
                              delegate: SliverChildBuilderDelegate((context, int index2) {
                                return Stack(
                                  children: <Widget>[
                                    Positioned(
                                      left: 150,
                                      top: 0,
                                      child: Container(
                                        width: 50,
                                        height: 50,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(25),
                                          border: Border.all(
                                              color: Colors.green, width: 2.0
                                          )
                                        ),
                                        alignment: Alignment.center,
                                        transform: Matrix4.rotationZ(.5),
                                        child: Text(
                                          infoList[index]["list"][index2]["type"],
                                          style: TextStyle(
                                            color: Colors.green,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 20
                                            // decoration: TextDecoration.underline,
                                            // decorationStyle: TextDecorationStyle.wavy,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      child: Flex(
                                        direction: Axis.vertical,
                                        children: <Widget>[
                                          Expanded(
                                            flex: 1,
                                            child: Container(
                                              alignment: Alignment(0.0, 0.0),
                                              child: Text(
                                                infoList[index]["list"][index2]["name"],
                                                style: TextStyle(
                                                  fontSize: 20.0,
                                                ),
                                              ),
                                              decoration: BoxDecoration(
                                                  border: Border(
                                                      bottom: BorderSide(
                                                          color: Colors.black26,
                                                          width: 1,
                                                          style: BorderStyle.solid
                                                      )
                                                  )
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 3,
                                            child: Container(
                                              alignment: Alignment(-1, -0.8),
                                              child: Text(
                                                infoList[index]["list"][index2]["introduction"],
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 1,
                                            child: Row(
                                              children: <Widget>[
                                                SizedBox(width: 70),
                                                SizedBox(
                                                  width: 35,
                                                  child: Offstage(
                                                    offstage: infoList[index]["list"][index2]["type"] != "任务",
                                                    child: FlatButton(
                                                      onPressed: () {
                                                        // showToast("修改");
                                                        Navigator.of(context).push(new MaterialPageRoute(
                                                            builder: (BuildContext context) => new DrawPage()));
                                                      },
                                                      padding: EdgeInsets.all(5),
                                                      child: Text(
                                                        "修改",
                                                        style: TextStyle(fontSize: 10),
                                                        textAlign: TextAlign.center,
                                                      ),
                                                      // color: Colors.white,
                                                      textColor: Colors.blue,
                                                    ),
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: 35,
                                                  child: FlatButton(
                                                    onPressed: () async {
                                                      SharedPreferences prefs = await SharedPreferences.getInstance();
                                                      prefs.setString("reviewId", infoList[index]["list"][index2]["_id"]);
                                                      Navigator.of(context).push(new MaterialPageRoute(
                                                          builder: (BuildContext context) => new ReviewPage()));
                                                    },
                                                    padding: EdgeInsets.all(5),
                                                    child: Text(
                                                      "查看",
                                                      style: TextStyle(fontSize: 10),
                                                    ),
                                                    // color: Colors.white,
                                                    textColor: Colors.blue,
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: 35,
                                                  child: FlatButton(
                                                    onPressed: () {
                                                      delete(infoList[index]["list"][index2], projectList[index]["_id"], index, index2);
                                                    },
                                                    padding: EdgeInsets.all(5),
                                                    child: Text(
                                                      "删除",
                                                      style: TextStyle(fontSize: 10),
                                                    ),
                                                    // color: Colors.white,
                                                    textColor: Colors.blue,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                      padding: EdgeInsets.all(5),
                                      margin: EdgeInsets.all(5),
                                      decoration: BoxDecoration(
                                        // color: Colors.pink,
                                        border: Border.all(
                                          color: Colors.black,
                                        ),
                                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                      ),
                                    )
                                  ],
                                );
                              },
                                childCount: infoList[index]["list"].length,
                              ),
                            ),
                            SliverToBoxAdapter(
                              child: Container(
                                padding: EdgeInsets.all(5),
                                margin: EdgeInsets.all(5),
                                width: 190,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  // color: Colors.pink,
                                  border: Border.all(
                                    color: Colors.black45,
                                  ),
                                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                                ),
                                child: FlatButton(
                                  child: Text(
                                    "+",
                                    style: TextStyle(
                                        fontSize: 100,
                                        color: Colors.black45
                                    ),
                                  ),
                                  onPressed: () async {
                                    SharedPreferences prefs = await SharedPreferences.getInstance();
                                    prefs.setString("projectId", projectList[index]["_id"]);
                                    Navigator.of(context).push(new MaterialPageRoute(
                                        builder: (BuildContext context) => new AddReviewPage()));
                                  },
                                )
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
            ),
            SizedBox(height: 10),
          ],
        );
      },
    );
  }

  Future<dynamic> getProjects() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString("userId");
    try {
      Response response = await Dio().get(
          Config.BASE_URL + "/project/getProject",
          queryParameters: {"userId": userId});
      projectList = response.data;
      // print(projectList);
      for (var j = 0; j < projectList.length; j ++) {
        GlobalKey globalKey = new GlobalKey();
        btnKeys2.add(globalKey);
      }
      for(var k = 0; k < projectList.length; k ++) {
        response = await Dio().post(
          Config.BASE_URL + "/project/getProjectDetail",
          data: {
            "reviews": projectList[k]["reviews"],
            "collections": projectList[k]["collections"],
          });
        infoList.add(response.data);
      }
      // print(infoList);
      return 1;
    } catch (e) {
      print(e);
    }
  }

  Future<dynamic> addProject(String name, String introduction) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString("userId");
    try {
      Response response = await Dio().post(
        Config.BASE_URL + "/project/addProject",
        data: {
          "name": name,
          "userId": userId,
          "introduction": introduction
        });
      if(response.data == 1) {
        getProjects().then((data) {
          setState(() {});
        });
        return true;
      } else {
        showToast(response.data);
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }

  Future<dynamic> delete(Map info, String projectId, int index, int index2) async {
    try {
      Response response;
      if(info["type"] == "任务") {
        response = await Dio().post(
            Config.BASE_URL + "/review/deleteReview",
            data: {
              "id": info["_id"],
              "projectId": projectId,
              "mediaId": info["mediaId"]
            });
      } else {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String userId = prefs.getString("userId");
        response = await Dio().post(
            Config.BASE_URL + "/collection/deleteCollection",
            data: {
              "id": info["_id"],
              "projectId": projectId,
              "userId": userId
            });
      }
      if(response.data["type"] == 1) {
        showToast("删除成功");
        List delInfoList = infoList[index]["list"];
        delInfoList.removeAt(index2);
        setState(() {
          infoList[index]["list"] = delInfoList;
        });
      } else {
        showToast("删除失败");
      }
    } catch (e) {
      print(e);
    }
  }

  Future<dynamic> showInfo() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      showToast(prefs.getKeys().toString());
    } catch (e) {
      print(e);
    }
  }

  _showDialog() async {
    TextEditingController _nameController = new TextEditingController();
    TextEditingController _introController = new TextEditingController();
    var alertDialog = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text("新增项目"),
            content: new SingleChildScrollView(
              child: new ListBody(
                  children: <Widget>[
                    Container(
                      width: 150,
                      child: TextField(
                        controller: _nameController,
                        decoration: InputDecoration(labelText: "名称",),
                      ),
                    ),
                    Container(
                      width: 150,
                      height: 150,
                      child: TextFormField(
                        maxLines: 3,
                        controller: _introController,
                        decoration: InputDecoration(labelText: "简介",),
                      ),
                    ),
                  ]
              ),
            ),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () async {
                  if(await addProject(_nameController.text, _introController.text))
                    Navigator.of(context).pop();
                  },
              ),
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        }
    ).then((value) => print(value));
    return alertDialog;
  }

  @override
  void initState() {
    super.initState();
    getProjects().then((data) {
      setState(() {});
    });
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    PopupMenu.context = this.context;
    return new Scaffold(
        appBar: new AppBar(
          elevation: 0.0,
          centerTitle: true,
          title: new Text(
            '我的项目',
            style: new TextStyle(fontSize: 20.0, color: Colors.white),
          ),
          actions: <Widget>[
            new IconButton(
              icon: new Icon(
                Icons.add_circle_outline,
                color: Colors.white,
              ),
              onPressed: () {
                _showDialog();
              },
            )
          ],
        ),
        body: _scrollView());
  }
}
